<?php


namespace Module\Message\Admin\Controller;


use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use ModStart\Admin\Concern\HasAdminQuickCRUD;
use ModStart\Admin\Layout\AdminCRUDBuilder;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Util\CRUDUtil;
use ModStart\Grid\Grid;
use ModStart\Grid\GridFilter;
use ModStart\Repository\Filter\RepositoryFilter;
use ModStart\Support\Concern\HasFields;
use Module\Message\Model\Message;
use Module\Message\Model\MessageCategory;
use Module\Message\Type\MessageStatus;

class MessageController extends Controller
{
    use HasAdminQuickCRUD;

    protected function crud(AdminCRUDBuilder $builder)
    {
        $builder
            ->init(Message::class)
            ->field(function ($builder) {
                /** @var HasFields $builder */
                $builder->id('id', 'ID');
                $builder->select('categoryId', '分类')->optionModel('message_category','id','title');
                $builder->richHtml('content', '内容');
                $builder->display('userId','接收人姓名')->hookRendering(function (  $field, $item, $index){
                    $adminModel = new \ModStart\Admin\Model\AdminUser();
                    $userModel = new \Module\Member\Util\MemberUtil();
                    if ($item->categoryId == 2) {
                        $user = $adminModel->where('id',$item->userId)->first();
                        return $user['username'];
                    } else {
                        $user = $userModel::get($item->userId);
                        return  $user['realname'];
                    }}
                );
                $builder->display('fromId','来源人姓名')->hookRendering(function ( $field, $item, $index) {
                    $adminModel = new \ModStart\Admin\Model\AdminUser();
                    $userModel = new \Module\Member\Util\MemberUtil();
                    if ($item->categoryId  == 1) {
                        $user = $adminModel->where('id',$item->fromId)->first();
                        return $user['username'];
                    } else {
                        $user = $userModel::get($item->fromId );
                        return $user['realname'];
                    }
                });
                $builder->type('status','状态')->type(MessageStatus::class,[
                   MessageStatus::UNREAD => 'danger',
                   MessageStatus::READ => 'success'
                ]);
                $builder->display('created_at', L('Created At'));
                $builder->display('updated_at', L('Updated At'));
            })
            ->gridFilter(function (GridFilter $filter) {
                $filter->eq('id', L('ID'));
                $filter->eq('status','状态');
            })
            ->title('留言管理列表')
            ->defaultOrder(['id', 'asc'])
            ->canSort(true);
    }
}
